// 判断非空
export function isNull(str) {
  return !!(!str && str !== 0 && typeof str !== 'boolean')
}

/**
 * @desc 判断是否是对象
 * @returns {String}
 */
export function typeObject(obj) {
  const type = Object.prototype.toString.call(obj)
  if (type === '[object Array]') {
    return 'Array'
  } else if (type === '[object Object]') {
    return 'Object'
  } else {
    return 'obj is not object or array'
  }
}

// 上传图片 为true时返回promise 是为了解决uploadHeaders修改不及时，导致上传没有携带token
export function beforeUploadImg(file, vue, imgWidth, imgHeight, imgSizes) {
  vue.uploadHeaders = {
    'X-KDADMIN-TOKEN': vue.$store.state.user.token
  }

  const isType = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isType) {
    vue.$message.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }

  const rightSizes = file.size / 1024 / 1024 < imgSizes
  if (!rightSizes) {
    if (imgSizes >= 1) {
      vue.$message.error(`上传图片大小不能超过 ${imgSizes}MB!`)
    } else {
      vue.$message.error(`上传图片大小不能超过 ${imgSizes * 1000}KB!`)
    }
    return false
  }

  // 不限制宽高
  if (imgWidth === 0 && imgHeight === 0) {
    return new Promise(rel => {
      setTimeout(rel, 0)
    })
  }

  // 限制宽高
  const isSize = new Promise(function(resolve, reject) {
    const width = imgWidth
    const height = imgHeight
    const _URL = window.URL || window.webkitURL
    const img = new Image()
    img.onload = function() {
      const valid = img.width <= width && img.height <= height
      valid ? resolve() : reject()
    }
    img.src = _URL.createObjectURL(file)
  }).then(
    () => {
      return file
    },
    () => {
      vue.$message.error(`上传图片像素大小不能超过 ${imgWidth}*${imgHeight}px!`)
      return Promise.reject()
    }
  )
  return isSize
}
/**
 * @description: 上传文件校验 为true时返回promise 是为了解决uploadHeaders修改不及时，导致上传没有携带token
 * @param file   文件
 * @param vue    当前上下文 this
 * @param option  {fileSizes、fileType、validNameTypeArr，nameErrMsg, imgWidth,imgHeight}
 * @return {Boolean}
 */
export function beforeUploadFile(file, vue, option) {
  // 文件格式校验
  const {
    fileType,
    fileSizes,
    validNameTypeArr,
    nameErrMsg,
    imgWidth,
    imgHeight } = option
  // 文件后缀名
  const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
  if (fileType) {
    if (fileType == 'video') {
      const fileTypeArr = ['avi', 'wmv', 'mpg', 'mpeg', 'mov', 'rm', 'ram', 'swf', 'flv', 'mp4', 'mp3', 'wma', 'avi', 'rm', 'rmvb', 'flv', 'mpg', 'mkv']
      if (!fileTypeArr.includes(fileSuffix)) {
        vue.$message.error('上传文件只能是 视频格式!')
        return false
      }
    } else if (fileType == 'img') {
      const fileTypeArr = ['jpg', 'jpeg', 'png']
      if (!fileTypeArr.includes(fileSuffix)) {
        vue.$message.error('上传图片只能是 JPG/PNG 格式!')
        return false
      }
    } else if (fileType == 'userValid' && validNameTypeArr.length) {
      // 使用者自定义校验
      if (!validNameTypeArr.includes(fileSuffix)) {
        vue.$message.error(nameErrMsg || '上传文件格式不正确!')
        return false
      }
    }
  }

  const rightSizes = file.size / 1024 / 1024 < fileSizes
  if (!rightSizes) {
    if (fileSizes >= 1) {
      vue.$message.error(`上传文件大小不能超过 ${fileSizes}MB!`)
    } else {
      vue.$message.error(`上传文件大小不能超过 ${fileSizes * 1000}KB!`)
    }
    return false
  }

  if (fileType == 'img' && imgWidth && imgHeight) {
    // 限制宽高
    return new Promise(function(resolve, reject) {
      const width = imgWidth
      const height = imgHeight
      const _URL = window.URL || window.webkitURL
      const img = new Image()
      img.onload = function() {
        const valid = img.width <= width && img.height <= height
        valid ? resolve() : reject()
      }
      img.src = _URL.createObjectURL(file)
    }).then(
      () => {
        return true
      },
      () => {
        vue.$message.error(`上传图片像素大小不能超过 ${imgWidth}*${imgHeight}px!`)
        return Promise.resolve(false)
      }
    )
  } else {
    return true
  }
}

// 导表
export function downloadFile(data, fileName) {
  if (!data) {
    return
  }

  const timeStr = new Date()
  const fileTime =
      timeStr.getFullYear() +
      '' +
      (timeStr.getMonth() < 9
        ? '0' + (timeStr.getMonth() + 1)
        : timeStr.getMonth() + 1) +
      '' +
      (timeStr.getDate() < 10 ? '0' + timeStr.getDate() : timeStr.getDate()) +
      '' +
      timeStr.getHours() +
      '' +
      timeStr.getMinutes() +
      '' +
      timeStr.getSeconds()
  const link = document.createElement('a')
  const blob = new Blob([data], {
    type: 'application/vnd.ms-excel'
  })
  link.style.display = 'none'
  link.href = URL.createObjectURL(blob)
  link.setAttribute('download', `${fileName}` + '.xlsx')
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
// 加减乘除运算
export const math = {
  // 乘法
  mul(arg1, arg2) {
    const r1 = arg1.toString()
    const r2 = arg2.toString()
    const d = arguments[2]
    const m = (r1.split('.')[1] ? r1.split('.')[1].length : 0) + (r2.split('.')[1] ? r2.split('.')[1].length : 0)
    const resultVal = Number(r1.replace('.', '')) * Number(r2.replace('.', '')) / Math.pow(10, m)
    return typeof d !== 'number' ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)))
  },
  // 除法
  div(arg1, arg2) {
    const r1 = arg1.toString()
    const r2 = arg2.toString()
    const d = arguments[2]
    const m = (r2.split('.')[1] ? r2.split('.')[1].length : 0) - (r1.split('.')[1] ? r1.split('.')[1].length : 0)
    const resultVal = Number(r1.replace('.', '')) / Number(r2.replace('.', '')) * Math.pow(10, m)
    return typeof d !== 'number' ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)))
  },
  // 加法
  add(arg1, arg2) {
    arg1 = arg1.toString()
    arg2 = arg2.toString()
    const arg1Arr = arg1.split('.')
    const arg2Arr = arg2.split('.')
    const d1 = arg1Arr.length === 2 ? arg1Arr[1] : ''
    const d2 = arg2Arr.length === 2 ? arg2Arr[1] : ''
    const maxLen = Math.max(d1.length, d2.length)
    const m = Math.pow(10, maxLen)
    const result = Number(((arg1 * m + arg2 * m) / m).toFixed(maxLen))
    const d = arguments[2]
    return typeof d === 'number' ? Number((result).toFixed(d)) : result
  },
  // 减法
  sub(arg1, arg2) {
    return this.add(arg1, -Number(arg2), arguments[2])
  }
}
